package mn.idax.exchange.otc.task;

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.elasticjob.lite.annotation.ElasticSimpleJob;
import com.google.common.collect.Lists;
import mn.idax.exchange.otc.enums.RedisPrefixKeyEnum;
import mn.idax.exchange.otc.service.UserService;
import mn.idax.exchange.otc.service.impl.RedisService;
import mn.idax.exchange.otc.util.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: jack_huang
 * @Date: 2019/8/22 17:38
 * 同步redis中被禁止下单的用户 到user 表状态
 * redis 中每天 utc 23:59过期 每天0点跑一次 考虑到和服务器时间作同步并且服务启动时执行 改为每小时跑一次
 * 更新user字段  冻结user放在了业务里
 */

//@ElasticSimpleJob(cron="0 0 0,12 * * ?")
@ElasticSimpleJob(cron = "0 0 0/1 * * ?")
@Component
public class SynchronizeOTCUserCreateOrderJob implements SimpleJob {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserService userService;


    @Override
    public void execute(ShardingContext shardingContext) {


        List<Integer> redisList = Lists.newArrayList();

        List<Integer> forbidOTCCreateorderUser = userService.getMoreThanThreeCancelUser();

        /**
         * 程序启动时把redis中取消三次的用户加入 同步到user表
         */
        String prifix = RedisPrefixKeyEnum.order_cancel_num.getKey().concat("*");
        Set<String> keys = stringRedisTemplate.keys(prifix);
        if (!keys.isEmpty()){
            for(String key : keys){
                String userIdString = key.substring(21);
                String cacheStrValue = redisService.getCacheStrValue(RedisPrefixKeyEnum.order_cancel_num.getKey().concat(userIdString));
                Integer redisValue = Integer.valueOf(cacheStrValue);
                if (redisValue > 2){
                    Integer userId = Integer.valueOf(userIdString);
                    redisList.add(Integer.valueOf(userId));
                    if (!forbidOTCCreateorderUser.contains(userId)){
                        //禁止
                        userService.forzenUserStatus(Integer.valueOf(userId));
                        LogUtils.info(this.getClass(), "frozenUserOtcCreateOrder userid  : " + userId);
                    }

                }
            }
        }

        forbidOTCCreateorderUser.removeAll(redisList);
        if (!forbidOTCCreateorderUser.isEmpty()){
            for (Integer integer : forbidOTCCreateorderUser) {
                //解禁
                userService.unforzenUserStatus(integer);
            }
        }

        LogUtils.info(this.getClass(), "unfrozenUserOtcCreateOrder users : " + JSON.toJSONString(forbidOTCCreateorderUser));
    }
}
